#include "Feed.h"
#include "rss_parser.h"
#include "RSS20Parser.h"


Feed::Feed(const string& url):url_(url),etag_(),data_(), easy_(url_, etag_)
{
	items_.clear();
	parser_=new RSS20Parser;
}


Feed::~Feed()
{
	delete parser_;
	
	map<string,Item*>::const_iterator it=items_.begin();
	Item* temp=NULL;
	while(it!=items_.end())
	{
		temp=it->second;
		it++;
		delete temp;
	}
	items_.clear();
}

/*reset url address, and free the memory kept in the map*/
void Feed::Reset(string& new_url)
{
	url_=new_url;
	easy_.Reset(url_);

	map<string,Item*>::const_iterator it=items_.begin();
	Item* temp=NULL;
	while(it!=items_.end())
	{
		temp=it->second;
		it++;
		delete temp;
	}
	items_.clear();
}

/*check the url of the RSS feed, get and store each item*/
void Feed::CheckFeed()
{

	switch (easy_.PerformRequest())
	{
	case 200:
		{
			etag_ = easy_.GetResponseEtag();
			data_ = easy_.GetResponseData();
			cout<<data_<<endl;
			break;
		} 	
	default:
		{
		}
	}	

	auto_ptr<TiXmlDocument> doc = auto_ptr<TiXmlDocument>(new TiXmlDocument());
	doc->Parse(data_.c_str());
	//doc->Print(stdout);

	//get root element
	const TiXmlElement* root = doc->RootElement();



	//iterate each Item
	for( const TiXmlElement* child = root->FirstChildElement()->FirstChildElement("item");
		child;
		child=child->NextSiblingElement())
	{
		Item *elem=parser_->ParseData(child);
		if(!elem)
			continue;
		items_[elem->getID()]=elem;
	}

}

